from starlette.endpoints import HTTPEndpoint
from starlette.responses import JSONResponse
from database import Session, engine
import datetime
from dao import DaoProblemTypeList
from model.ModProblemTypeList import ProblemTypeList as ptl
import logging



class ProblemTypeList(HTTPEndpoint):

    def __init__(self, scope):
        super().__init__(scope)
        self._logger = logging.getLogger(type(self).__name__)

    async def get(self, request):
        session = Session()
        try:
          # protype = request.query_params["protype"]
           return  DaoProblemTypeList.get_problem_info(session)
        finally:
            session.close()

    async def post(self, request):
        session = Session()
        try:
            dict_pro = await request.json()
            pro = ptl()
            message_str = ""
            if len(dict_pro["proname"]) > 0:
                pro.proname = dict_pro.get("proname")
            else:
                message_str = "问题内容"
            pro.protype = "0"
            pro.photoflag = "1"
            a = DaoProblemTypeList.get_problem_max(session)
            b = int(a)+1
            pro.proid = str(b).zfill(2)
            if len(message_str) > 0:
                last_str = message_str[-1]
                if last_str == "、":
                    message_str = message_str[:-1]
                message_str = "请确认：" + message_str + "等信息是否填写完整！"
                return JSONResponse({"result": "2", "message_str": message_str})
            DaoProblemTypeList.insert_pro(session, pro)
            session.commit()
            return JSONResponse({"result": "1"})
        except Exception as e:
            self._logger.info(e)
            session.rollback()
            return JSONResponse({"result": "0"})
        finally:
            session.close()
